package com.example.myapplication.ui.activity.search

import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView
import com.example.myapplication.R
import com.example.myapplication.arouter.ARouterPath
import com.example.myapplication.bean.article.ArticleBean
import com.example.myapplication.bean.collect.WebsiteCollectBean
import com.example.myapplication.dialog.OperationDialog
import com.example.myapplication.ui.adapter.ArticleAdapter
import com.example.myapplication.ui.adapter.HotKeyAdapter
import com.kun.base.env.Env
import com.kun.base.ui.AbsBaseActivity
import com.scwang.smart.refresh.header.ClassicsHeader
import kotlinx.android.synthetic.main.activity_search.*
import kotlinx.android.synthetic.main.activity_search.refresh_layout
import kotlinx.android.synthetic.main.fragment_home.*

/**
 *搜索的activity
 *
 * @author : Kun
 * @date : 2021/6/9
 * @time : 14:03
 */
@Route(path = ARouterPath.SEARCH)
class SearchActivity : AbsBaseActivity() {
    private var index = 0
    private lateinit var articleAdapter: ArticleAdapter

    private lateinit var hotKeyAdapter: HotKeyAdapter
    private var mList = mutableListOf<WebsiteCollectBean>()

    private lateinit var searchViewModel: SearchViewModel
    override fun getLayoutId(): Int {
        return R.layout.activity_search
    }

    override fun initViewModel() {
        searchViewModel = getActivityScopeViewModel(SearchViewModel::class.java)
        searchViewModel.searchRequest.hotKeyResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                mList.addAll(t.data!!)
                hotKeyAdapter.notifyDataChanged()
            }
        })
        initSearchResult()
        initAddCollectArticle()
        initDelCollectArticle()
    }

    override fun initView() {
        hotKeyAdapter = HotKeyAdapter(this, mList)
        flow_layout.adapter = hotKeyAdapter

        refresh_layout!!.setRefreshHeader(ClassicsHeader(this))
        articleAdapter = ArticleAdapter(R.layout.item_article, null)
        articleAdapter.loadMoreModule.loadMoreView = SimpleLoadMoreView()

        rv_search.layoutManager = LinearLayoutManager(this)
        rv_search.adapter = articleAdapter

        initListener()

        searchViewModel.requestHotKey()
    }

    /**
     * 事件监听
     */
    private fun  initListener(){
        flow_layout.setOnTagClickListener { _, position, _ ->
            val bean = mList[position]
            et_search.setText(bean.name)
            return@setOnTagClickListener true
        }
        flow_layout.setOnClickListener {  }
        iv_back.setOnClickListener { finish() }
        tv_search.setOnClickListener {
            index = 0
            getData()
            flow_layout.visibility = View.GONE
        }

        articleAdapter.loadMoreModule.setOnLoadMoreListener {
            //加载更多
            index++
            getData()
        }
        refresh_layout!!.setOnRefreshListener {
            //刷新数据
            index = 0
            getData()
        }

        articleAdapter.setOnItemClickListener { _, _, position ->
            //文章点击
            val articleBean = articleAdapter.getItem(position)
            startToWeb(articleBean.link, articleBean.title)
        }
        articleAdapter.addChildClickViewIds(R.id.view_collect)
        articleAdapter.setOnItemChildClickListener { _, childView, position ->
            val articleBean = articleAdapter.getItem(position)
            if (childView.id == R.id.view_collect) {
                if (articleBean.collect) {
                    searchViewModel.requestDelCollectArticle(articleBean.id)
                } else {
                    searchViewModel.requestAddCollectArticle(articleBean.id)
                }
            }
        }
        articleAdapter.setOnItemLongClickListener { _, _, position ->
            val articleBean = articleAdapter.getItem(position)
            showOperationDialog(articleBean)
            return@setOnItemLongClickListener true

        }
    }
    /**
     * 获取数据
     */
    private fun getData() {
        searchViewModel.requestSearchList(index, et_search.text.toString())
    }

    /**
     * 搜索结果
     */
    private fun initSearchResult() {
        searchViewModel.searchRequest.searchListResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                if (t.data!!.curPage == 1) {
                    articleAdapter.setList(t.data!!.datas)
                } else {
                    articleAdapter.addData(t.data!!.datas)
                }
                if (t.data!!.curPage >= t.data!!.pageCount) {
                    articleAdapter.loadMoreModule.loadMoreEnd()
                } else {
                    articleAdapter.loadMoreModule.loadMoreComplete()
                }
            }
            articleAdapter.loadMoreModule.loadMoreComplete()
            refresh_layout!!.finishRefresh()
        })
    }

    /**
     * 收藏文章接口回调
     */
    private fun initAddCollectArticle() {
        searchViewModel.collectRequest.addArticleResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                articleAdapter.let {
                    val list = it.data
                    for (i in list) {
                        if (t.data == i.id) {
                            i.collect = true
                        }
                    }
                    it.notifyDataSetChanged()
                }
            }
        })
    }

    /**
     * 取消收藏文章接口回调
     */
    private fun initDelCollectArticle() {
        searchViewModel.collectRequest.delArticleResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                articleAdapter.let {
                    val list = it.data
                    for (i in list) {
                        if (t.data == i.id) {
                            i.collect = false
                        }
                    }
                    it.notifyDataSetChanged()
                }
            }
        })
    }
    /**
     * 跳转到web页面
     */
    private fun startToWeb(linkUrl: String, title: String) {
        var url = linkUrl
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = Env.getDomain() + url
        }

        ARouter.getInstance().build(ARouterPath.WEB).withString("url", url)
            .withString("title", title).navigation()
    }

    /**
     * 显示操作弹窗
     */
    private fun showOperationDialog(articleBean: ArticleBean) {
        OperationDialog(this).apply {
            addSelectItems("打开链接", if (articleBean.collect) "取消收藏" else "收藏")
            setOnSelectListener(object : OperationDialog.OnSelectListener {
                override fun onSelect(name: String, position: Int) {
                    if (position == 0) {
                        startToWeb(articleBean.link, articleBean.title)
                    } else {
                        if (articleBean.collect) {
                            searchViewModel.requestDelCollectArticle(articleBean.id)
                        } else {
                            searchViewModel.requestAddCollectArticle(articleBean.id)
                        }
                    }
                    dismiss()
                }
            })
        }.show()
    }
}